﻿'
'19-10-11 
'Copyright (c) 2011, Yonel Meza Avila
'All rights reserved.
'Liberado bajo licencia New BSD License (BSD) 
'
'
'Dialogo para metadata y envio del documento

Imports System.Windows.Forms
Imports System.Net
Imports System.Security.Cryptography
Imports System.Security.Cryptography.MD5
Imports Microsoft.Office.Interop.Word
Imports System.IO

Public Class DialogEnviar


    Private Function GetMd5Hash(ByVal input As String) As String
        Dim md5Hash As MD5 = MD5.Create()

        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input))

        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New StringBuilder()

        ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i

        ' Return the hexadecimal string.
        Return sBuilder.ToString()

    End Function 'GetMd5Hash
    'Función para verificación de los campos
    Private Function checkCampos() As Boolean

        If Trim(refTxt.Text) <> "" Then
            If Trim(asuntoTxt.Text) <> "" Then
                If Trim(comentarioTxt.Text) <> "" Then
                    If categoriasCmb.SelectedIndex <> -1 Then
                        If tiposCmb.SelectedIndex <> -1 Then
                            If Not usuariosLstb.Enabled And usuariosLstb.SelectedIndex <> -1 Then
                                If Not enviarChb.Checked Or enviarChb.Checked And Trim(obsTxt.Text) <> "" Then
                                    Return True
                                Else
                                    MsgBox("Debe colocar algun comentario para el envio")
                                    Return False
                                End If

                            Else
                                MsgBox("Debe seleccionar algún usuario para enviarle el documento")
                                Return False
                            End If
                        Else
                            MsgBox("Debe seleccionar un tipo de documento")
                            Return False
                        End If

                    Else
                        MsgBox("Debe seleccionar una categoría")
                        Return False
                    End If

                Else
                    MsgBox("Debe colocar un comentario del anexo")
                    Return False
                End If

            Else
                MsgBox("Debe colocar el asunto")
                Return False
            End If
        Else
            MsgBox("Debe colocar el Número de referencia")
            Return False
        End If
    End Function
    'Enviar archivo acutal y metadada
    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        Dim settings As MySettings = New MySettings
        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Dim id_documento As String
        Dim Doc As New Word.Document
        Doc = Globals.ThisAddIn.Application.ActiveDocument
        If (Doc.Path = "" Or Doc.Saved = False) Then
            If MsgBox("El documento necesita estar guardado antes de poder ser enviado" + Chr(13) + Chr(10) + "¿Desea guardarlo para continuar?", MsgBoxStyle.YesNo + MsgBoxStyle.Question) = MsgBoxResult.Yes Then
                Try
                    Doc.Save()
                Catch fileException As Exception
                    MsgBox("No se puede continuar")
                    Return
                End Try
            Else
                Return
            End If
        End If
        If Not checkCampos() Then
            Me.DialogResult = System.Windows.Forms.DialogResult.None

            Return
        End If
        Dim filename As String = Doc.Path + "\" + Doc.Name, filenameNP As String = Doc.Name
        If MsgBox("El documento se cerrará para ser enviado" + Chr(13) + Chr(10) + "¿Desea continuar?", MsgBoxStyle.YesNo + MsgBoxStyle.Question) = MsgBoxResult.Yes Then
            Doc.SaveAs2(filenameNP + ".html", WdSaveFormat.wdFormatFlatXML)
            Doc.Close()
            Dim raditext As String = File.ReadAllText(filenameNP + ".html")
            My.Computer.FileSystem.DeleteFile(filenameNP + ".html")
            Dim myWebClient As New WebClient()
            Dim col = New Collections.Specialized.NameValueCollection
            col.Add("user", settings.user)
            Dim passmd5 As String = Me.GetMd5Hash(settings.password)
            col.Add("password", passmd5)
            myWebClient.QueryString = col
            Dim responseArray As Byte() = myWebClient.UploadFile(settings.quipuxserver + "/upload.php", "POST", filename)
            Globals.ThisAddIn.Application.Documents.Open(filename)

            If (Encoding.ASCII.GetString(responseArray) <> "ERROR") Then
                id_documento = Encoding.UTF8.GetString(responseArray)
                Dim servicio As QuipuxServices.wordquipux = New QuipuxServices.wordquipux
                Dim resultados As QuipuxServices.ClaveValor
                Try
                    servicio.Url = settings.quipuxserver + "/server.php?wsdl"
                Catch
                    MsgBox("URL no válida: " + settings.quipuxserver + "/server.php?wsdl")
                    Me.DialogResult = System.Windows.Forms.DialogResult.None

                    Return
                End Try
                Dim referencia, asunto, desc_anexo, categoria, tipo, para, nomb_archivo, enviar_documento, obs_documento, cc As String
                referencia = refTxt.Text
                asunto = asuntoTxt.Text
                desc_anexo = comentarioTxt.Text
                'raditext = "" 'Falta leer html del documento
                categoria = categoriasCmb.SelectedItem.Clave
                tipo = tiposCmb.SelectedItem.Clave
                para = ""
                For Each item In usuariosLstb.SelectedIndices
                    resultados = usuariosLstb.Items.Item(item)
                    para = para + resultados.Clave

                Next
                cc = ""
                For Each item In usuariosccLstb.SelectedIndices
                    resultados = usuariosccLstb.Items.Item(item)
                    cc = cc + resultados.Clave

                Next
                nomb_archivo = filenameNP
                If enviarChb.Checked Then
                    enviar_documento = 1
                    obs_documento = obsTxt.Text
                Else
                    enviar_documento = 0
                    obs_documento = ""

                End If
                If comocontenidoRbnt.Checked Then
                    id_documento = "0"
                ElseIf comoanexoRbtn.Checked Then
                    raditext = ""
                End If
                resultados = servicio.send_document_metadata(settings.user, GetMd5Hash(settings.password), referencia, asunto, desc_anexo, raditext, categoria, tipo, para, id_documento, nomb_archivo, enviar_documento, obs_documento, cc)
                Me.DialogResult = System.Windows.Forms.DialogResult.OK
            Else
                MsgBox("No se pudo enviar el archivo")
                Me.DialogResult = System.Windows.Forms.DialogResult.None
            End If
        End If
        MsgBox("Documento enviado satisfactoriamente")
    End Sub
    'Botón de cancelar
    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub
    'Carga de la forma, llena combo de categorías, tipos de documentos y lista de usuarios
    Private Sub Dialog2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Panel1.Hide()
        Me.Width = 460
        Dim servicio As QuipuxServices.wordquipux = New QuipuxServices.wordquipux
        Dim settings As MySettings = New MySettings
        Dim resultados As Array
        Dim clavevalor As QuipuxServices.ClaveValor
        Try
            servicio.Url = settings.quipuxserver + "/server.php?wsdl"
        Catch
            MsgBox("URL no válida: " + settings.quipuxserver + "/server.php?wsdl")
            Me.Close()
            Return
        End Try
        tiposCmb.ValueMember = "Clave"
        tiposCmb.DisplayMember = "Valor"
        categoriasCmb.ValueMember = "Clave"
        categoriasCmb.DisplayMember = "Valor"
        usuariosLstb.ValueMember = "Clave"
        usuariosLstb.DisplayMember = "Valor"
        usuariosccLstb.ValueMember = "Clave"
        usuariosccLstb.DisplayMember = "Valor"

        resultados = servicio.get_tipo_documento(settings.user, GetMd5Hash(settings.password))
        For Each clavevalor In resultados
            'tipos.Add(d.Valor)
            tiposCmb.Items.Add(clavevalor)

        Next
        resultados = servicio.get_tipo_categoria(settings.user, GetMd5Hash(settings.password))
        For Each clavevalor In resultados
            'tipos.Add(d.Valor)
            categoriasCmb.Items.Add(clavevalor)
        Next

    End Sub
    ' Habilita/Deshabilita la caja de texto para comentario de envío
    Private Sub enviarChb_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If enviarChb.Checked Then
            obsTxt.Enabled = True
        Else
            obsTxt.Enabled = False
        End If
    End Sub

    Private Sub concopiaBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles concopiaBtn.Click
        If concopiaBtn.Text = "Agregar CC >>" Then
            Panel1.Show()
            Me.Width = 681
            concopiaBtn.Text = "Quitar CC >>"
        Else
            Panel1.Hide()
            Me.Width = 460
            concopiaBtn.Text = "Agregar CC >>"
            usuariosccLstb.SelectedIndex = -1

        End If

    End Sub


    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buscarccTxt.TextChanged
        Dim servicio As QuipuxServices.wordquipux = New QuipuxServices.wordquipux
        Dim settings As MySettings = New MySettings
        Dim resultados As Array
        Dim alguno As Boolean = False
        If Trim(buscarccTxt.Text).Length > 2 Then
            resultados = servicio.get_usuarios(settings.user, GetMd5Hash(settings.password), Trim(buscarccTxt.Text))
            usuariosccLstb.Items.Clear()
            For Each clavevalor In resultados
                'tipos.Add(d.Valor)
                usuariosccLstb.Items.Add(clavevalor)
                alguno = True
            Next

        End If
        If alguno Then
            usuariosccLstb.Enabled = True
        Else
            usuariosccLstb.Enabled = False
        End If
    End Sub

    Private Sub TextBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buscarccTxt.Enter
        If Trim(buscarccTxt.Text.ToUpper()) = "BUSCAR" Then
            buscarccTxt.Text = ""
        End If
    End Sub

    Private Sub buscarTxt_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buscarTxt.TextChanged
        Dim servicio As QuipuxServices.wordquipux = New QuipuxServices.wordquipux
        Dim settings As MySettings = New MySettings
        Dim resultados As Array
        Dim alguno As Boolean = False
        If Trim(buscarTxt.Text).Length > 2 Then
            resultados = servicio.get_usuarios(settings.user, GetMd5Hash(settings.password), Trim(buscarTxt.Text))
            usuariosLstb.Items.Clear()
            For Each clavevalor In resultados
                'tipos.Add(d.Valor)
                usuariosLstb.Items.Add(clavevalor)
                alguno = True
            Next

        End If
        If alguno Then
            usuariosLstb.Enabled = True
        Else
            usuariosLstb.Enabled = False
        End If
    End Sub

    Private Sub buscarTxt_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buscarTxt.Enter
        If Trim(buscarTxt.Text.ToUpper()) = "BUSCAR" Then
            buscarTxt.Text = ""
        End If
    End Sub

    Private Sub buscarTxt_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buscarTxt.Leave
        If Trim(buscarTxt.Text.ToUpper()) = "" Then
            buscarTxt.Text = "Buscar"
        End If
    End Sub

    Private Sub buscarccTxt_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buscarccTxt.Leave
        If Trim(buscarccTxt.Text.ToUpper()) = "" Then
            buscarccTxt.Text = "Buscar"
        End If

    End Sub

    Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comocontenidoRbnt.CheckedChanged
        If comocontenidoRbnt.Checked Then
            MsgBox("No es recomendado enviarlo sólo como contenido, ya que es posible que se pieda partes del formato del documento." + Chr(13) + "Seleccione como anexo o ambos para evitar este problema.")

        End If

    End Sub
End Class
